/*
 * $Id$
 *
 * Copyright 2008 HuangHuang. All rights reserved.
 */
package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.apache.tapestry.form.LabeledPropertySelectionModel;
import org.apache.tapestry.IPage;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.valid.ValidationDelegate;
import org.apache.tapestry.valid.ValidationConstraint;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.Bean;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.javaforge.tapestry.spring.annotations.InjectSpring;
import com.crm.service.ICustomerService;
import com.crm.service.IListboxService;
import com.crm.model.*;
import com.crm.web.util.ListboxPropertySelectionModel;
import com.crm.web.util.Constants;

import java.util.Date;
import java.util.Calendar;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class CustomerInfo extends BasePage implements PageBeginRenderListener {

    private Log log = LogFactory.getLog(getClass());
    private static final String NONE = "none";

    @InjectState("userSession")
    public abstract User getUserSession();                

    @InjectSpring("customerService")
    public abstract ICustomerService getCustomerServ();

    @InjectSpring("listboxService")
    public abstract IListboxService getListboxServ();

    @Bean
    public abstract ValidationDelegate getDelegate();

    @InjectPage("CustomerAll")
    public abstract CustomerAll getCustomerAllPage();

    public abstract LProduct getProductSelected();

    public abstract LCustLevel getLevelSelected();

    public abstract LCustSource getSourceSelected();

    public abstract String getCustomerName();

    public abstract String getCountry();

    public abstract String getProvince();

    public abstract String getCity();

    public abstract String getAddress();

    public abstract String getWebsite();

    public abstract String getComment();

    public abstract String getCallbackMsg();

    public abstract void setCallbackMsg(String callbackMsg);

    public IPropertySelectionModel getSourceSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_CUST_SOURCE),
                Constants.DFT_SELECT_LABEL);
    }

    public IPropertySelectionModel getLevelSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_CUST_LEVEL),
                Constants.DFT_SELECT_LABEL);
    }

    public IPropertySelectionModel getProductSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_PRODUCT),
                Constants.DFT_SELECT_LABEL);
    }

    public IPage goback() {
        return getCustomerAllPage();
    }

    public String infoSubmit() {
        try {
            if (getDelegate().getHasErrors() || isSameName(getCustomerName()) ||
                    (getWebsite() != null && isSameWebsite(getWebsite()))) {
                return getPageName();
            }
            getCustomerServ().create(newCustomer());
            log.info(getUserSession().getUsername() + ": Added a new customer!");
            return getCustomerAllPage().getPageName();
        } catch (Exception e) {
            String exceptionString = "系统异常！ " + e.getMessage();
            log.error(getUserSession().getUsername() + ": " + exceptionString);
            e.printStackTrace();
            getDelegate().record(exceptionString, ValidationConstraint.CONSISTENCY);
            return getPageName();
        }
    }

    /**
     * Create a customer instance.
     *
     * @return Customer A instance of customer
     */
    public Customer newCustomer() {
        Customer customerInfo = new Customer();
        customerInfo.setCustomerName(getCustomerName().trim());
        customerInfo.setCountry(null == getCountry() ? NONE : getCountry().trim());
        customerInfo.setProduct(getProductSelected());
        customerInfo.setLevel(getLevelSelected());
        customerInfo.setSource(getSourceSelected());
        customerInfo.setDateOfSave(new Date());
        customerInfo.setCity(getCity() == null ? NONE : getCity().trim());
        customerInfo.setWebsite(getWebsite() == null ? NONE : getWebsite().trim());
        customerInfo.setAddress(getAddress() == null ? NONE : getAddress().trim());
        customerInfo.setProvince(getProvince() == null ? NONE : getProvince().trim());
        customerInfo.setComments(getComment() == null ? NONE : getComment());
        customerInfo.setUser(getUserSession());
        String weekOfYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        weekOfYear = weekOfYear + String.valueOf(Calendar.getInstance().get(Calendar.WEEK_OF_YEAR));
        customerInfo.setWeekOfYear(weekOfYear);
        return customerInfo;
    }

    private boolean isSameWebsite(String website) {
        String sameWebsite = getCustomerServ().getSameWebsite(website);
        if (sameWebsite != null) {
            String message = "已经存在名为【" + sameWebsite + "】的网址！";
            getDelegate().record(message, ValidationConstraint.CONSISTENCY);
            return true;
        }
        return false;
    }

    private boolean isSameName(String customerName) {
        String sameCustomerName = getCustomerServ().getSameName(customerName);
        if (sameCustomerName != null) {
            String message = "已经存在名为【" + sameCustomerName + "】的客户！";
            getDelegate().record(message, ValidationConstraint.CONSISTENCY);
            return true;
        }
        return false;
    }

    /**
     * save and continue add.
     *
     * @return String - The name of page.
     */
    public String saveAdd() {
        infoSubmit();
        return getPageName();
    }

    public void onRefresh() {
        getDelegate().clearErrors();
    }

    /**
     * lisenter：check validity name of customer 。This is have to submit all form.
     *
     * @return String - The message result.
     */
    public String checkCustomerName() {
        if (getDelegate().getHasErrors()) {
            return getPageName();
        }
        if (isSameName(getCustomerName())) {
            return getPageName();
        } else {
            String message = "该客户名称有效！";
            getDelegate().record(message, ValidationConstraint.CONSISTENCY);
            return getPageName();
        }
    }

    /**
     * lisenter：check validity name of customer.
     * use ajax submit then update pointed components
     */
    public void checkSameName() {
        onRefresh();
        if (getCustomerName() == null) {
            setCallbackMsg("客户名称必须填写！");
        } else {
            String sameCustomerName = getCustomerServ().getSameName(getCustomerName());
            if (null != sameCustomerName) {
                setCallbackMsg("已经存在名为【" + sameCustomerName + "】的客户！");
            } else {
                setCallbackMsg("该客户名称有效！");
            }
        }
    }

    public void pageBeginRender(PageEvent event) {
        if (getUserSession() == null)
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
    }

}
